// pages/Domains/DomainList.tsx
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Plus, Play, Square, Pause, Trash2, Monitor, Eye } from 'lucide-react';
import { useDomainStore } from '../../stores/domainStore';
import { useApp } from '../../App';
import { ROUTES } from '../../router';
import type { DomainSummary } from '../../types/api';

const DomainList: React.FC = () => {
  const navigate = useNavigate();
  const { currentConnection } = useApp();
  const {
    domains,
    loading,
    error,
    fetchDomains,
    startDomain,
    shutdownDomain,
    forceStopDomain,
    suspendDomain,
    resumeDomain,
    deleteDomain
  } = useDomainStore();

  const [selectedDomains] = useState<Set<string>>(new Set());

  useEffect(() => {
    if (currentConnection) {
      fetchDomains(currentConnection);
    }
  }, [currentConnection, fetchDomains]);

  const handleStartDomain = async (name: string) => {
    if (!currentConnection) return;
    try {
      await startDomain(currentConnection, name);
    } catch (error) {
      console.error('Failed to start domain:', error);
    }
  };

  const handleShutdownDomain = async (name: string) => {
    if (!currentConnection) return;
    try {
      await shutdownDomain(currentConnection, name);
    } catch (error) {
      console.error('Failed to shutdown domain:', error);
    }
  };

  const handleForceStopDomain = async (name: string) => {
    if (!currentConnection) return;
    if (window.confirm(`Are you sure you want to force stop "${name}"?`)) {
      try {
        await forceStopDomain(currentConnection, name);
      } catch (error) {
        console.error('Failed to force stop domain:', error);
      }
    }
  };

  const handleSuspendDomain = async (name: string) => {
    if (!currentConnection) return;
    try {
      await suspendDomain(currentConnection, name);
    } catch (error) {
      console.error('Failed to suspend domain:', error);
    }
  };

  const handleResumeDomain = async (name: string) => {
    if (!currentConnection) return;
    try {
      await resumeDomain(currentConnection, name);
    } catch (error) {
      console.error('Failed to resume domain:', error);
    }
  };

  const handleDeleteDomain = async (name: string) => {
    if (!currentConnection) return;
    if (window.confirm(`Are you sure you want to delete "${name}"? This action cannot be undone.`)) {
      try {
        await deleteDomain(currentConnection, name);
      } catch (error) {
        console.error('Failed to delete domain:', error);
      }
    }
  };

  const getDomainStatus = (state: string) => {
    switch (state.toLowerCase()) {
      case 'running':
        return { color: 'text-green-500', bgColor: 'bg-green-500/10', label: 'Running' };
      case 'shut off':
        return { color: 'text-red-500', bgColor: 'bg-red-500/10', label: 'Shut Off' };
      case 'paused':
        return { color: 'text-yellow-500', bgColor: 'bg-yellow-500/10', label: 'Paused' };
      default:
        return { color: 'text-gray-500', bgColor: 'bg-gray-500/10', label: state };
    }
  };

  const formatMemory = (memory: number) => {
    return `${Math.round(memory / 1024)} MB`;
  };

  if (!currentConnection) {
    return (
      <div className="text-center py-12">
        <p className="text-lg text-gray-400 mb-4">No connection selected</p>
        <button
          onClick={() => navigate(ROUTES.CONNECTIONS)}
          className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors"
        >
          Go to Connections
        </button>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-500"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-center py-8">
        <p className="text-red-500 mb-4">{error}</p>
        <button
          onClick={() => fetchDomains(currentConnection)}
          className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors"
        >
          Retry
        </button>
      </div>
    );
  }

  return (
    <div>
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-2xl font-bold">Virtual Machines</h2>
        <button
          onClick={() => navigate(ROUTES.DOMAIN_NEW)}
          className="flex items-center gap-2 px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors"
        >
          <Plus size={16} />
          New VM
        </button>
      </div>

      {domains.length === 0 ? (
        <div className="text-center py-12">
          <Monitor className="mx-auto mb-4 text-gray-400" size={48} />
          <p className="text-lg text-gray-400 mb-4">No virtual machines found</p>
          <button
            onClick={() => navigate(ROUTES.DOMAIN_NEW)}
            className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors"
          >
            Create VM
          </button>
        </div>
      ) : (
        <div className="grid gap-4">
          {domains.map((domain: DomainSummary) => {
            const status = getDomainStatus(domain.state);
            const isSelected = selectedDomains.has(domain.name);

            return (
              <div
                key={domain.name}
                className={`p-4 rounded-lg border transition-all ${
                  isSelected
                    ? 'border-purple-500 bg-purple-500/10'
                    : 'border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900'
                } hover:shadow-lg cursor-pointer`}
                onClick={() => navigate(ROUTES.DOMAIN_DETAIL(domain.name))}
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-4">
                    <div className="flex items-center gap-2">
                      <Monitor size={20} className="text-gray-400" />
                      <div>
                        <h3 className="font-semibold">{domain.name}</h3>
                        <p className="text-sm text-gray-500">{domain.uuid}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <span className={`px-2 py-1 text-xs rounded ${status.bgColor} ${status.color}`}>
                        {status.label}
                      </span>
                    </div>
                  </div>

                  <div className="flex items-center gap-2">
                    <div className="text-sm text-gray-500">
                      <span className="mr-4">{formatMemory(domain.memory)}</span>
                      <span>{domain.vcpus} vCPUs</span>
                    </div>

                    <div className="flex items-center gap-1">
                      {domain.state.toLowerCase() === 'running' ? (
                        <>
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              handleShutdownDomain(domain.name);
                            }}
                            className="p-2 text-yellow-500 hover:bg-yellow-500/10 rounded transition-colors"
                            title="Shutdown"
                          >
                            <Square size={16} />
                          </button>
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              handleSuspendDomain(domain.name);
                            }}
                            className="p-2 text-blue-500 hover:bg-blue-500/10 rounded transition-colors"
                            title="Suspend"
                          >
                            <Pause size={16} />
                          </button>
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              navigate(ROUTES.DOMAIN_CONSOLE(domain.name, 'vnc'));
                            }}
                            className="p-2 text-purple-500 hover:bg-purple-500/10 rounded transition-colors"
                            title="Console"
                          >
                            <Eye size={16} />
                          </button>
                        </>
                      ) : domain.state.toLowerCase() === 'paused' ? (
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            handleResumeDomain(domain.name);
                          }}
                          className="p-2 text-green-500 hover:bg-green-500/10 rounded transition-colors"
                          title="Resume"
                        >
                          <Play size={16} />
                        </button>
                      ) : (
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            handleStartDomain(domain.name);
                          }}
                          className="p-2 text-green-500 hover:bg-green-500/10 rounded transition-colors"
                          title="Start"
                        >
                          <Play size={16} />
                        </button>
                      )}

                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          handleForceStopDomain(domain.name);
                        }}
                        className="p-2 text-red-500 hover:bg-red-500/10 rounded transition-colors"
                        title="Force Stop"
                      >
                        <Square size={16} />
                      </button>

                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          handleDeleteDomain(domain.name);
                        }}
                        className="p-2 text-red-500 hover:bg-red-500/10 rounded transition-colors"
                        title="Delete"
                      >
                        <Trash2 size={16} />
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

export default DomainList;